<template lang="html">
  <el-dialog :title="dialogTitle" :append-to-body="true" :close-on-click-modal="false" :show-close="false"
    v-model="dialogVisible" @close="close" width="600px">
    <el-container v-loading="dialogLoading" class="book-detail-container">
      <el-main>
        <el-form label-width="125px" :model="bookEntity" ref="bookForm" class="edit-pane" :inline="false"
          :rules="bookFormRules">
          <el-row>
            <el-col :span="16">
              <el-form-item label="书籍名称" prop="title">
                <el-input v-model="bookEntity.title" style="width: 200px"></el-input>
              </el-form-item>
              <el-form-item label="作者" prop="author">
                <el-input v-model="bookEntity.author" style="width: 200px"></el-input>
              </el-form-item>
              <el-form-item label="分类/子分类" required>
                <el-form-item prop="category">
                  <el-input v-model="bookEntity.category" style="width: 95px;margin-right: 10px;"></el-input>
                </el-form-item>
                <el-form-item prop="subCategory">
                  <el-input v-model="bookEntity.subCategory" style="width: 95px"></el-input>
                </el-form-item>
              </el-form-item>
              <el-form-item label="书籍来源" prop="sourceType">
                <el-select v-model="bookEntity.sourceType" placeholder="请选择书籍来源" style="width: 200px;">
                  <el-option v-for="item in options.bookSourceTypeSelector" :key="item.value" :label="item.label"
                    :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-image :src="bookEntity.coverPicture" class="book-cover" lazy fit="cover">
                <template #error>
                  <div class="image-slot">
                    <el-image :src="noneCover"></el-image>
                  </div>
                </template>
              </el-image>
            </el-col>
          </el-row>
          <el-form-item label="更新状态" prop="sourceType">
            <el-select v-model="bookEntity.completed" placeholder="是否完本" style="width: 200px;">
              <el-option v-for="item in options.completedSelector" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="封面图片" prop="coverPicture">
            <el-input v-model="bookEntity.coverPicture" style="width: 400px"></el-input>
          </el-form-item>
          <el-form-item label="目录地址" prop="spiderUrl">
            <el-input v-model="bookEntity.spiderUrl" style="width: 400px"></el-input>
          </el-form-item>
          <el-form-item label="简介" prop="description">
            <el-input type="textarea" v-model="bookEntity.description" style="width: 400px;"></el-input>
          </el-form-item>
        </el-form>
      </el-main>
    </el-container>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">关闭</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="js">
import { onMounted, ref, inject } from 'vue';
import { ElMessage } from 'element-plus';
import _ from 'lodash';
const { onSuccess, matchBookSource } = inject('bookMgrProvide');
const { getMultiSelectOptions, selectNames } = inject('selectCollection');
import noneCover from '@/assets/noneConver.jpg';
import { add, modify } from '@/api/bookMgr';

const dialogVisible = ref(false); // 弹窗是否可见
const dialogLoading = ref(false); // 弹窗加载状态
const isEdit = ref(false); // 是否编辑状态
const dialogTitle = ref(""); // 弹窗标题
const bookForm = ref(null); // 表单
const initBookEntity = () => {
  return {
    id: '', // 书籍ID
    title: '', // 书名
    author: '', // 坐着
    sourceType: '', // 书籍来源
    description: '', // 书籍描述
    coverPicture: '', // 封面图片
    category: '', // 分类
    subCategory: '', // 子分类
    spiderUrl: '', // 爬虫地址
    completed: false, // 是否完本
  }
};

const bookEntity = ref(initBookEntity());
const bookFormRules = {
  title: [
    { required: true, message: '请输入书名', trigger: 'blur' },
    { min: 1, max: 100, message: '书名长度在 1 到 100 个字符之间', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入作者', trigger: 'blur' },
    { min: 1, max: 50, message: '作者长度在 1 到 50 个字符之间', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请输入分类', trigger: 'blur' },
    { min: 1, max: 50, message: '分类长度在 1 到 50 个字符之间', trigger: 'blur' }
  ],
  subCategory: [
    { required: true, message: '请输入子分类', trigger: 'blur' },
    { min: 1, max: 50, message: '子分类长度在 1 到 50 个字符之间', trigger: 'blur' }
  ],
  sourceType: [
    { required: true, message: '请选择书籍来源', trigger: 'change' }
  ],
  coverPicture: [
    { required: true, message: '请输入封面图片地址', trigger: 'blur' },
    { type: 'url', message: '封面图片地址格式不正确', trigger: 'blur' }
  ],
  spiderUrl: [
    { required: true, message: '请输入目录地址', trigger: 'blur' },
    { type: 'url', message: '目录地址格式不正确', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入书籍简介', trigger: 'blur' },
    { min: 1, max: 500, message: '描述长度在 1 到 500 个字符之间', trigger: 'blur' }
  ],
  completed: [
    { required: true, message: '请选择更新状态', trigger: 'change' }
  ]
};
const options = ref({
  bookSourceTypeSelector: [],
  completedSelector: [
    { label: '完本', value: true },
    { label: '连载', value: false }
  ]
});

/**
 * 关闭弹窗
 */
function close() {
  if (dialogLoading.value) {
    return false;
  }
  dialogVisible.value = false;
  bookEntity.value = initBookEntity();
}

/**
 * 保存
 */
function save() {
  dialogLoading.value = true;
  saveDebounce();
}

const saveDebounce = _.debounce(() => {
  bookForm.value.validate((vaild) => {
    if (!vaild) {
      dialogLoading.value = false;
      ElMessage.error("数据验证不通过，请检查输入!");
      return;
    }

    let book = Object.assign({}, bookEntity.value);
    let fun = isEdit.value ? modify : add;
    fun(book).then((res) => {
      if (res == null || !res.isSuccess) {
        ElMessage.error(res.message || "操作失败");
        return;
      }
      ElMessage.success("保存成功");
      dialogLoading.value = false;
      onSuccess();
      if (!isEdit.value) {
        matchBookSource({
          id: res.data,
          title: book.title,
          author: book.author,
        });
      }
      close();
    }).finally(() => {
      dialogLoading.value = false;
    });
  });
}, 500);

/**
 * 初始化选项数据
 */
function initOptions() {
  const keys = [selectNames.bookSourceTypeEnum];
  getMultiSelectOptions(...keys).then((res) => {
    options.value.bookSourceTypeSelector = res.getOptions(selectNames.bookSourceTypeEnum);
  });
}

/**
 *  打开弹窗
 * @param book 书籍对象
 */
function open(book) {
  dialogLoading.value = false;
  if (bookForm.value) {
    bookForm.value.resetFields();
  }
  if (book && book.id) {
    isEdit.value = true;
    dialogTitle.value = "编辑书籍";
    bookEntity.value = Object.assign({}, book);
  } else {
    isEdit.value = false;
    dialogTitle.value = "添加书籍";
    bookEntity.value = initBookEntity();
  }

  dialogVisible.value = true;
}

onMounted(() => {
  initOptions();
});

defineExpose({
  openDialog: open,
});

</script>
<style lang="">

</style>
